package com.prs.crm.action.pm;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;

import com.prs.crm.action.FlowAction;
import com.prs.crm.annotation.Clew;
import com.prs.crm.context.Constrains;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.Attachment;
import com.prs.crm.domain.doc.DocLevel;
import com.prs.crm.domain.doc.Document;
import com.prs.crm.domain.pm.PmGroup;
import com.prs.crm.domain.pm.PmProject;
import com.prs.crm.domain.pm.PmRelatStage;
import com.prs.crm.domain.pm.PmStage;
import com.prs.crm.domain.pm.PmStageType;
import com.prs.crm.service.doc.DocLevelService;
import com.prs.crm.service.doc.DocumentService;
import com.prs.crm.service.pm.PmDocService;
import com.prs.crm.service.pm.PmRelatStageService;
import com.prs.crm.service.pm.PmStageService;
import com.prs.crm.service.pm.PmStageTypeService;

public class PmStageAction extends FlowAction<PmStage>{
	private PmProject pmProject;
	private PmStage pmStage;
	private PmStage parentPmStage;
	private PmRelatStage pmRelatStage;
	private Document document;
	private DocumentService documentService;
	private PmStageService pmStageService;
	private DocLevelService docLevelService;
	private PmRelatStageService pmRelatStageService;
	private PmStageTypeService pmStageTypeService;
	
	private PaginationSupport pagination;
	private Integer[] ids;
	private Integer[] docIds;
	
	private File upload;
	private String uploadFileName;
	private File selectDoc;
	private String selectDocFileName;
	private String pmBudget;
	private String delayTime;
	private String stageRelation;
	
	private Collection<PmGroup> pmExeGroup;
	private Collection<DocLevel> docLevels;
	private Collection<TreeNode> nodes;
	private Collection<PmStage> peerStages;
	private static Collection<PmRelatStage> relatStages;
	private static Collection<Document> relatDocs;
	private Collection<PmStageType> pmStageTypes;
	
	static{
		relatStages = new ArrayList<PmRelatStage>();
		relatDocs = new ArrayList<Document>();
	}
	
	@Action("projectStage")
	public String projectStage() {
		return SUCCESS;
	}
	
	//项目阶段的树形结构
	@Action("treeStage")
	public String treeStage() {
		return SUCCESS;
	}
	
	//创建、编辑项目阶段
	@Action("editPmStage")
	public String editPmStage() {		
		if(this.pmExeGroup == null) {
			pmExeGroup = new ArrayList<PmGroup>();
		}
//		pmExeGroup.add(pmProject.getPrincipal());
		for(PmGroup group : pmProject.getMemberGroup()) {
			pmExeGroup.add(group);
		}
		
		peerStages = this.getPmStageService().getPeerStage(pmProject, parentPmStage);
		docLevels = this.getDocLevelService().getAllDocLevel();
		pmStageTypes = this.getPmStageTypeService().getAllPmStageType();
		return SUCCESS;
	}
	
	@Action(value="removeStage",results={@Result(name="success",type="json",params={"root","prompt"})})
	public String removeStage() {
		try
		{
			this.getPmStageService().remove(pmStage);
			this.setPrompt("success");
		}
		catch (Exception e)
		{
			this.setPrompt("error");
		}
		return SUCCESS;
	}	
	
	//提交项目阶段
	@Clew(results={"success"})
	@Action(value="submitPmStage",results={@Result(name="success",type="redirect",location="viewPmStage?pmStage=${pmStage.id}"),
			@Result(name="error",type="chain",location="editPmStage")})
	public String submitPmStage() {		
		if(pmStage.getTitle() == null || pmStage.getTitle().trim().equals("")) {
			this.addActionError("请输入阶段名称");
			return ERROR;
		}
		if(pmStage.getStartTime() == null || pmStage.getEndTime() == null) {
			this.addActionError("开始结束时间不能为空");
			return ERROR;
		}
		if(!ToolKits.isNumeric(pmBudget)) {
			this.addActionError("预算应为数字格式");
			return ERROR;
		}
		if(parentPmStage != null) {
			Double budget = parentPmStage.getBudget();
			Double total = 0.0;
			for(PmStage stage : parentPmStage.getChildren()) {
				total += stage.getBudget();
			}
			total += Double.parseDouble(pmBudget);
			if(total > budget) {
				this.addActionError("本级预算之和不能大于上级预算");
				return ERROR;
			}
		}else {
			Double budget = pmProject.getBudget();
			Double total = 0.0;
			Collection<PmStage> stages = this.getPmStageService().getRootStage(pmProject);
			for(PmStage stage : stages) {
				total += stage.getBudget();
			}
			total += Double.parseDouble(pmBudget);
			if(total > budget) {
				this.addActionError("本级预算之和不能大于项目预算");
				return ERROR;
			}
		}
		
		pmStage.setBudget(Double.valueOf(pmBudget));
		pmStage.setProject(pmProject);
		pmStage.setUpStage(parentPmStage);
		pmStage.setState(Constrains.PM_STATE_INIT);
		this.getPmStageService().submitStage(pmStage, upload, uploadFileName);
		
		for(PmRelatStage stage : relatStages) {
			stage.setId(null);
			stage.setSrcPmStage(pmStage);
			
			this.getPmRelatStageService().save(stage);
		}
		for(Document doc : relatDocs) {
			File file = new File(doc.getAttach().getPath());
			String fileName = doc.getAttach().getName();
			doc.setId(null);
			doc.setProject(pmProject);
			doc.setStage(pmStage);
			this.getDocumentService().submitDocument(doc);//, file, fileName);
		}
		
		relatDocs.clear();
		relatStages.clear();
		this.setPrompt("创建项目阶段成功");
		return SUCCESS;
	}
	
	//浏览项目阶段
	@Action(value="viewPmStage")
	public String viewPmStage()
	{
		return SUCCESS;
	}
	
	//构造项目阶段树形
	@Action(value="loadStageTree",results={@Result(name="success",type="json",params={"root","nodes"})})
	public String loadStageTree() {
		nodes = new ArrayList<TreeNode>();
		Collection<PmStage> stages = this.getPmStageService().getRootStage(pmProject);
		for(PmStage stage : stages) {
			TreeNode node = new TreeNode();
			node.setId(stage.getId().toString());
			node.setText(stage.getTitle());
			nodes.add(node);
			addChildNode(stage,node);
		}
		return SUCCESS;
	}
	
	//递归添加阶段树形节点
	private void addChildNode(PmStage parent,TreeNode parentNode) {
		if(parent.getChildren() != null) {
			for(PmStage stage:parent.getChildren()) {
				TreeNode node = new TreeNode();
				node.setId(stage.getId().toString());
				node.setText(stage.getTitle());
				parentNode.addChildNode(node);
				addChildNode(stage,node);
			}
		}
	}
	
	@Action(value="appendRelatStage",results={@Result(name="success",type="redirect",location="editPmStage?pmProject=${pmProject.id}&parentPmStage=${parentPmStage.id}&pmStage=${pmStage.id}"),
			@Result(name="error",type="chain",location="editPmStage")})
	public String appendRelatStage() {
		if(delayTime != null && !delayTime.trim().equals("")) {
			if(!ToolKits.isInteger(delayTime)) {
				this.addActionError("延搁时间应为整数型");
				return ERROR;
			}
		}
		
		PmRelatStage rs = new PmRelatStage();
		rs.setId(relatStages.size());
		rs.setTargetPmStage(pmRelatStage.getTargetPmStage());
		rs.getTargetPmStage().getTitle();
		if(delayTime == null || delayTime.trim().equals("")) {
			rs.setDelay(0.0);
		}else {
			rs.setDelay(Double.parseDouble(delayTime));
		}
		if(stageRelation.equals("无")) {
			rs.setRelation(Constrains.PM_STAGE_NONE);
		}else if(stageRelation.equals("完成开始(FS)")) {
			rs.setRelation(Constrains.PM_STAGE_FS);
		}else if(stageRelation.equals("开始开始(SS)")) {
			rs.setRelation(Constrains.PM_STAGE_SS);
		}else if(stageRelation.equals("完成完成(FF)")) {
			rs.setRelation(Constrains.PM_STAGE_FF);
		}else if(stageRelation.equals("开始完成(SF)")) {
			rs.setRelation(Constrains.PM_STAGE_SF);
		}
		relatStages.add(rs);
		
		return SUCCESS;
	}
	
	@Action(value="removeRelatStage",results={@Result(name="success",type="redirect",location="editPmStage?pmProject=${pmProject.id}&parentPmStage=${parentPmStage.id}&pmStage=${pmStage.id}"),
			@Result(name="error",type="chain",location="editPmStage")})
	public String removeRelatStage() {
		if(ids == null) {
			this.addActionError("请选择要删除的前置阶段");
			return ERROR;
		}
		for(Integer id : ids) {
			for(PmRelatStage stage : relatStages) {
				if(stage.getId() == id) {
					relatStages.remove(stage);
					break;
				}
			}
		}
		return SUCCESS;
	}
	
	@Action(value="appendRelatDoc",results={@Result(name="success",type="redirect",location="editPmStage?pmProject=${pmProject.id}&parentPmStage=${parentPmStage.id}&pmStage=${pmStage.id}"),
			@Result(name="error",type="chain",location="editPmStage")})
	public String appendRelatDoc() {
		if(document.getName() == null || document.getName().trim().equals("")) {
			this.addActionError("请正确填写文档名称");
			return ERROR;
		}
		if (document.getDocumentcode() == null || document.getDocumentcode().trim().equals("")) {
			this.addActionError("请正确填写文档编码");
			return ERROR;
		}
		if(document.getType() == null) {
			this.addActionError("请选择文档类型");
			return ERROR;
		}
		if(selectDoc == null) {
			this.addActionError("请选择文档");
			return ERROR;
		}

		document.setId(relatDocs.size());
		Attachment attach = new Attachment();
		attach.setPath(selectDoc.getPath());
		attach.setName(selectDocFileName);
		document.setAttach(attach);
		document.getType().getName();
		document.getLevel().getName();
		
		relatDocs.add(document);
	
		return SUCCESS;
	}
	
	@Action(value="removeRelatDoc",results={@Result(name="success",type="redirect",location="editPmStage?pmProject=${pmProject.id}&parentPmStage=${parentPmStage.id}&pmStage=${pmStage.id}"),
			@Result(name="error",type="chain",location="editPmStage")})
	public String removeRelatDoc() {
		if(docIds == null) {
			this.addActionError("请选择要删除的文档");
			return ERROR;
		}
		for(Integer id : docIds) {
			for(Document doc : relatDocs) {
				if(doc.getId() == id) {
					relatDocs.remove(doc);
					break;
				}
			}
		}
		return SUCCESS;
	}
	
	public PmProject getPmProject() {
		return pmProject;
	}
	public void setPmProject(PmProject pmProject) {
		this.pmProject = pmProject;
	}
	public PmStage getPmStage() {
		return pmStage;
	}
	public void setPmStage(PmStage pmStage) {
		this.pmStage = pmStage;
	}
	public PmStageService getPmStageService() {
		return pmStageService;
	}
	public void setPmStageService(PmStageService pmStageService) {
		this.pmStageService = pmStageService;
	}
	public PaginationSupport getPagination() {
		return pagination;
	}
	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}
	public Integer[] getIds() {
		return ids;
	}
	public void setIds(Integer[] ids) {
		this.ids = ids;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public DocLevelService getDocLevelService() {
		return docLevelService;
	}

	public void setDocLevelService(DocLevelService docLevelService) {
		this.docLevelService = docLevelService;
	}

	public Collection<DocLevel> getDocLevels() {
		return docLevels;
	}

	public void setDocLevels(Collection<DocLevel> docLevels) {
		this.docLevels = docLevels;
	}

	public PmStage getParentPmStage() {
		return parentPmStage;
	}

	public void setParentPmStage(PmStage parentPmStage) {
		this.parentPmStage = parentPmStage;
	}

	public String getPmBudget() {
		return pmBudget;
	}

	public void setPmBudget(String pmBudget) {
		this.pmBudget = pmBudget;
	}

	public Collection<TreeNode> getNodes() {
		return nodes;
	}

	public void setNodes(Collection<TreeNode> nodes) {
		this.nodes = nodes;
	}

	public Collection<PmStage> getPeerStages() {
		return peerStages;
	}

	public void setPeerStages(Collection<PmStage> peerStages) {
		this.peerStages = peerStages;
	}

	public void setDelayTime(String delayTime) {
		this.delayTime = delayTime;
	}

	public String getDelayTime() {
		return delayTime;
	}

	public void setStageRelation(String stageRelation) {
		this.stageRelation = stageRelation;
	}

	public String getStageRelation() {
		return stageRelation;
	}

	public void setPmRelatStage(PmRelatStage pmRelatStage) {
		this.pmRelatStage = pmRelatStage;
	}

	public PmRelatStage getPmRelatStage() {
		return pmRelatStage;
	}

	public void setPmRelatStageService(PmRelatStageService pmRelatStageService) {
		this.pmRelatStageService = pmRelatStageService;
	}

	public PmRelatStageService getPmRelatStageService() {
		return pmRelatStageService;
	}

	public void setRelatStages(Collection<PmRelatStage> relatStages) {
		this.relatStages = relatStages;
	}

	public Collection<PmRelatStage> getRelatStages() {
		return relatStages;
	}

	public void setRelatDocs(Collection<Document> relatDocs) {
		PmStageAction.relatDocs = relatDocs;
	}

	public Collection<Document> getRelatDocs() {
		return relatDocs;
	}

	public void setDocIds(Integer[] docIds) {
		this.docIds = docIds;
	}

	public Integer[] getDocIds() {
		return docIds;
	}

	public File getSelectDoc() {
		return selectDoc;
	}

	public void setSelectDoc(File selectDoc) {
		this.selectDoc = selectDoc;
	}

	public String getSelectDocFileName() {
		return selectDocFileName;
	}

	public void setSelectDocFileName(String selectDocFileName) {
		this.selectDocFileName = selectDocFileName;
	}

	public void setPmExeGroup(Collection<PmGroup> pmExeGroup) {
		this.pmExeGroup = pmExeGroup;
	}

	public Collection<PmGroup> getPmExeGroup() {
		return pmExeGroup;
	}

	public void setPmStageTypes(Collection<PmStageType> pmStageTypes) {
		this.pmStageTypes = pmStageTypes;
	}

	public Collection<PmStageType> getPmStageTypes() {
		return pmStageTypes;
	}

	public void setPmStageTypeService(PmStageTypeService pmStageTypeService) {
		this.pmStageTypeService = pmStageTypeService;
	}

	public PmStageTypeService getPmStageTypeService() {
		return pmStageTypeService;
	}

	public Document getDocument() {
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public DocumentService getDocumentService() {
		return documentService;
	}

	public void setDocumentService(DocumentService documentService) {
		this.documentService = documentService;
	}


}
